package xkp.lesson4;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端收发分离
 * 主线程发送数据
 * 子线程等待接收数据
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //此处socket连接服务器
        //所有的网络通信都是基于socket IP+PORT
        //客户端的IP默认是本机IP地址
        //端口号为TCP/IP协议栈随机分配
        Socket socket = new Socket("192.168.93.60",12345);
        //网络传输为全双工模式
        //此处只要连接成功立刻启动子线程等待接收数据
        new Thread(){
            @Override
            public void run() {
                DataInputStream dataInputStream = null;
                try {
                    dataInputStream = new DataInputStream(socket.getInputStream());
                    while(true){
                        //不管两端哪一端强行关闭socket，都会造成读取数据异常
                        String revStr = dataInputStream.readUTF();
                        System.out.println(revStr);
                    }
                } catch (IOException e) {
                    //e.printStackTrace();
                }finally {
                    try {
                        dataInputStream.close();
                        socket.close();
                        System.out.println("服务器异常关闭!!!!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //主线程负责发送数据
        Scanner scanner = new Scanner(System.in);
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        while(true){
            //遇到回车为一行
            //获取控制台数据
            String sendStr = scanner.nextLine();
            //发送
            dataOutputStream.writeUTF(sendStr);
            dataOutputStream.flush();
        }
    }
}

